from django.db import connection
from django.apps import apps


class TenantMigrationRouter:

    def __is_scoped_app(self,app_label: str) -> bool:
        """
        Django admin ,auth app都不存在scoped，因而不是 scoped app,不需要独占schema
        """
        app_instance = apps.get_app_config(app_label)
        return getattr(app_instance,'scoped',False)
    
    def allow_migrate(self,db,app_label,model_name=None,**options):
        target_schema=connection.primary_schema # 我的目标schema,稍后看如何设置

        # 1，如果当前的锁定的schema是public，且当前的django应用不是业务应用，比如auth，admin应用(django自带的)
        if target_schema == 'public' and not self.__is_scoped_app(app_label):
            return None

        # 2.如果当前的锁定schema不是public,且当前的django应用必须使用自己的schema
        if target_schema != 'public' and self.__is_scoped_app(app_label):
            return None


        #否则拒绝同步数据
        return False